package com.jc.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.jc.subject.common.entity.PageResult;
import com.jc.subject.common.enums.IsDeletedFlagEnum;
import com.jc.subject.common.util.IdWorkerUtil;
import com.jc.subject.common.util.LoginUtil;
import com.jc.subject.domain.convert.SubjectCategoryConverter;
import com.jc.subject.domain.convert.SubjectInfoConverter;
import com.jc.subject.domain.entity.SubjectCategoryDO;
import com.jc.subject.domain.entity.SubjectInfoDO;
import com.jc.subject.domain.entity.SubjectLabelDO;
import com.jc.subject.domain.entity.SubjectOptionDO;
import com.jc.subject.domain.handler.HandlerFactory;
import com.jc.subject.domain.handler.SubjectStrategy;
import com.jc.subject.domain.redis.RedisUtil;
import com.jc.subject.domain.service.SubjectCategoryDomainService;
import com.jc.subject.domain.service.SubjectInfoDomainService;
import com.jc.subject.infra.basic.entity.*;
import com.jc.subject.infra.basic.service.*;
import com.jc.subject.infra.entity.UserInfo;
import com.jc.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author gongjiawei
 * @Date 2024/6/5 21:22
 * @注释
 */


@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

@Resource
private SubjectInfoService subjectInfoService;

@Resource
private SubjectMappingService subjectMappingService;

@Resource
private SubjectLabelService subjectLabelService;
@Resource
private SubjectEsService subjectEsService;
@Resource
private RedisUtil redisUtil;
private static final String RANK_KEY = "subject_rank";
@Resource
 private UserRpc userRpc;
@Resource
private HandlerFactory handlerFactory;
    @Override
    public void add(SubjectInfoDO subjectInfoDO) {

        //将题目信息插入题目信息表 TODO
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoDO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);

        subjectInfoDO.setId(subjectInfo.getId());
        //将信息插入单选，多选，判断或简答表中，这里采用工厂加策略模式
        SubjectStrategy strategy = handlerFactory.getStrategy(subjectInfoDO.getSubjectType());
        strategy.add(subjectInfoDO);
        List<Integer> categoryIds = subjectInfoDO.getCategoryIds();
        List<Integer> labelIds = subjectInfoDO.getLabelIds();
        List<SubjectMapping> subjectMappingList =new ArrayList<>();

        categoryIds.forEach(
                category->{
                    labelIds.forEach(
                            label->{
                                SubjectMapping subjectMapping=new SubjectMapping();
                                subjectMapping.setCategoryId(Long.valueOf(category));
                                subjectMapping.setLabelId(Long.valueOf(label));
                                subjectMapping.setSubjectId(subjectInfo.getId());
                                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                                subjectMappingList.add(subjectMapping);
                            }
                    );
                }

        );
        subjectMappingService.batchInsert(subjectMappingList);

        //同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoDO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("vip");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
       //redis放入zadd计入排行榜

        long timestamp = System.currentTimeMillis();
        double result = timestamp / 1e13;
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1-result);

    }

    @Override
    public List<SubjectLabelDO> queryLabel(SubjectInfoDO subjectInfoDO) {
        return null;
    }

    @Override
    public Boolean update(SubjectLabelDO subjectLabelDO) {
        return null;
    }

    @Override
    public Boolean delete(SubjectLabelDO subjectLabelDO) {
        return null;
    }

    @Override
    public PageResult<SubjectInfoDO> getSubjectPage(SubjectInfoDO subjectInfoDO) {
        PageResult<SubjectInfoDO> pageResult=new PageResult<>();
        pageResult.setPageSize(subjectInfoDO.getPageSize());
        pageResult.setPageNo(subjectInfoDO.getPageNo());
        int start= (subjectInfoDO.getPageNo()-1)*subjectInfoDO.getPageSize();

        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoDO);
        int count=subjectInfoService.countByCondition(subjectInfo,subjectInfoDO.getLabelId(),subjectInfoDO.getCategoryId());

        if (count==0)return pageResult;
        List<SubjectInfo> subjectInfoList=subjectInfoService.queryPage(
                subjectInfo,
                subjectInfoDO.getLabelId(),
                subjectInfoDO.getCategoryId(),
                start,
                subjectInfoDO.getPageSize()
        );
        List<SubjectInfoDO> subjectInfoDOS = SubjectInfoConverter.INSTANCE.convertInfoListToDoList(subjectInfoList);
        pageResult.setRecords(subjectInfoDOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoDO querySubjectInfo(SubjectInfoDO subjectInfoDO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoDO.getId());
        SubjectStrategy strategy = handlerFactory.getStrategy(subjectInfo.getSubjectType());
        SubjectOptionDO optionBO = strategy.query(subjectInfo.getId().intValue());
        SubjectInfoDO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);

        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);

        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());

        List<SubjectLabel> labelList = subjectLabelService.batchquery(labelIdList);

        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());

        bo.setLabelName(labelNameList);
//        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
//        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
//        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;


    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoDO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoDO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoDO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
            SubjectInfoDO subjectInfoBO = new SubjectInfoDO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }
}
